package com.silences.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//数据库连接
public class JDBCUtil {

    //私有化四个属性     static 静态属性，程序启动就加载意思
    private static String url=null;
    private static String driver=null;
    private static String user =null;
    private static String password =null;

    //加载静态模块
    static {
        //创建Properties对象，加载数据库配置文件：db.properties
        Properties pt = new Properties();
        InputStream in = JDBCUtil.class.getResourceAsStream("/db.properties");
        try {
              pt.load(in);
              //获取数据库配置文件的值，根据键值对方式去取
              url=pt.getProperty("url");
              driver=pt.getProperty("driver");
              user=pt.getProperty("user");
              password=pt.getProperty("password");
              Class.forName(driver);//加载数据库驱动
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    // 定义获取数据库连接的静态方法
    public static Connection getConn() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }
    //关闭资源方法
    public  static void close(PreparedStatement ps, Connection conn, ResultSet rs){
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(conn !=null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(rs !=null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

    public static String getDriver() {
        return driver;
    }
}
